function nologin() {
    mdui.alert('请登录', '未登录', function () {
        mdui.alert('登录');
        window.location.href = tem + '/html/login.html';
    });
}
// 清空 #file-elements 并获取对映路径的所有文件，回写 #file-elements
function load_file_elements(path) {
    let div = $("#file-elements");
    $.ajax({
        url: api + "/api/listfile",
        dataType: 'json',
        type: 'GET',
        data: {
            "path": path
        },
        success: function (data) {
            let code = data.code;
            switch (code) {
                case 0:
                    div.html("");
                    let array = data.items;
                    for (let i = 0; i < array.length; i++) {
                        load_file_item(array[i], div);
                    }
                    break;
                case -1:
                    mdui.snackbar({
                        message: '未知错误' + data.message,
                    });
                    break;
                case 403:
                    nologin();
                    break;
            }
        }
    });
}

// 使用 data 填充模板 append 到 div 下面，同步函数
// data 一个 LogicFile 元素，div 要显示的div
function load_file_item(data, div) {
    let template = tem + "/template/file_element.html";
    switch (data.FileType) {
        case "dir":
            data.LogicFileName = data.LogicPath;
            data.FileIcon = "class";
            template = tem + "/template/dir_element.html";
            break;
        case "text":
            data.FileIcon = "text_fields";
            break;
        case "document":
            data.FileIcon = "description";
            break;
        case "audio":
            data.FileIcon = "audiotrack";
            break;
        case "video":
            data.FileIcon = "ondemand_video";
            break;
        case "image":
            data.FileIcon = "perm_media";
            break;
        case "grahpics":
            data.FileIcon = "grain";
            break;
        case "software":
            data.FileIcon = "android";
            break;
        case "archive":
            data.FileIcon = "archive";
            break;
        case "misc":
            data.FileIcon = "dashboard";
            break;
        case "mobile":
            data.FileIcon = "apps";
            break;
        default:
            data.FileIcon = "insert_drive_file";
    }
    $.ajax({
        url: template,
        type: "GET",
        dataType: 'html',
        success: function (template) {
            if (data.FileType === 'dir') {
                div.append(Mustache.render(template, data));
            } else {
                div.prepend(Mustache.render(template, data));
            }
            get_file_element(data);
        }
    });
}

// 使用 uuid 获取文件信息
function get_file_element(data) {
    let item = $("#" + data.LogicFileID + "-body"); // 获取内容框
    $.ajax({
        url: tem + "/template/file_sub_element.html",
        // 需要 CreateDate ModifiDate FileSize isPublicLogicFileName
        type: "GET",
        dataType: 'html',
        success: function (template) {
            data.isPublic = data.Public === 0 ? "未" : "已";
            data.FileSize = bytesToSize(data.FileSize);
            item.html(Mustache.render(template, data));
        }
    });
}

function bytesToSize(bytes) {
    if (bytes === 0) return '0 B';
    let sizes = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
    let i = Math.floor(Math.log(bytes) / Math.log(1024));
    return (bytes / Math.pow(1024, i)).toFixed(2) + ' ' + sizes[i];
}

function downloadfile(uuid) {
    $.ajax({
        url: api + "/api/getdownloadurl",
        type: "GET",
        dataType: 'json',
        data: {uuid: uuid},
        success: function (data) {
            switch (data.code) {
                case 0:
                    let urls = data.urls;
                    if (urls.length === 0) {
                        mdui.snackbar({
                            message: '没有可用的下载地址',
                        });
                    } else {
                        window.open(urls[0]);
                    }
                    break;
                default:
                    mdui.snackbar({
                        message: '获取下载地址失败',
                    });
            }
        }
    });
}

function viewfile(uuid) {
    $.ajax({
        url: api + "/api/getdownloadurl",
        type: "GET",
        dataType: 'json',
        data: {uuid: uuid},
        success: function (data) {
            switch (data.code) {
                case 0:
                    let urls = data.urls;
                    if (urls.length === 0) {
                        mdui.snackbar({
                            message: '无预览',
                        });
                    } else {
                        let content1 = '<a class="media" href="' + urls[0] + '"></a></br></br></br></br></br></br></br></br></br></br></br></br></br></br></br></br></br></br>';
                        mdui.dialog({
                            title: '预览',
                            content: content1,
                            buttons: [
                                {
                                    text: '关闭'
                                }
                            ],
                            onOpen: function (inst) {
                                $('a.media').media();
                            }
                        });
                    }
                    break;
                default:
                    mdui.snackbar({
                        message: '无预览',
                    });
            }
        }
    });
}

function deletDom(uuid) {
    $("#" + uuid).remove();
    $("#divider-" + uuid).remove();
}

function deletfile(uuid) {
    $.ajax({
        url: api + "/api/deletefile",
        type: "POST",
        dataType: "json",
        data: {uuid: uuid},
        success: function (data) {
            deletDom(uuid);
            switch (data.code) {
                case 0:
                    mdui.snackbar({
                        message: '已经被移动到回收站',
                    });
                    break;
                case 1:
                    mdui.snackbar({
                        message: '已经被删除',
                    });
                    break;
            }
        }
    });
}
/*------------------------------------------------------geturl----------------------------------------------*/
function geturl(uuid) {
    $.ajax({
        url: api + "/api/geturl",
        type: "GET",
        dataType: "text",
        data: {uuid: uuid},
        success: function (data) {

            mdui.dialog({
                title: '分享链接',
                content: data,
                buttons: [
                    {
                        text: '关闭'
                    }
                ]
            });
        }
    });
}
/*------------------------------------------------------geturl----------------------------------------------*/

function jumpto(path) {
    PATH = path;
    load_file_elements(path);
    let separator = "<span class=\"mdui-typo-caption-opacity\">/</span>";
    let dir = "<button class=\"mdui-btn mdui-ripple\" onclick=\"jumpto('{{ path }}')\">{{ name }}</button>";

    let path_bar = $("#path_bar");
    path_bar.html("");
    path_bar.append(separator);
    path_bar.append(Mustache.render(dir, {name: "根目录", path: "/"}));
    path_bar.append(separator);

    let strs = path.split("/");
    for (let i = 1; i < strs.length - 1; i++) {
        path_bar.append(Mustache.render(dir,
            {
                name: strs[i],
                path: pathBuilder(strs, i + 1)
            }
        ));
        path_bar.append(separator);
    }
}

function pathBuilder(strs, t) {
    let ans = "";
    for (let i = 0; i < t; i++) {
        if (strs[i] === "") {
            ans += "/";
        } else {
            ans += strs[i];
        }
    }
    ans += "/";
    return ans;
}

function searchfile(key, type) {
    let path_bar = $("#path_bar");
    let ans = "<span class=\"mdui-typo-subheading-opacity\">{{ ans }} 的搜索结果</span>";
    path_bar.html("");
    path_bar.append(Mustache.render(ans, {ans: key}));

    let div = $("#file-elements");
    $.ajax({
        url: api + "/api/searchfile",
        dataType: 'json',
        type: 'GET',
        data: {
            "type": type,
            "key": key
        },
        success: function (data) {
            let code = data.code;
            switch (code) {
                case 0:
                    div.html("");
                    let array = data.items;
                    for (let i = 0; i < array.length; i++) {
                        load_file_item(array[i], div);
                    }
                    break;
                case -1:
                    mdui.snackbar({
                        message: '未知错误' + data.message,
                    });
                    break;
                case 403:
                    nologin();
                    break;
            }
        }
    });
}

function get_recent() {
    let div = $("#file-elements");
    $.ajax({
        url: api + "/api/searchfile",
        dataType: 'json',
        type: 'GET',
        data: {
            "order": "yes",
        },
        success: function (data) {
            let code = data.code;
            switch (code) {
                case 0:
                    div.html("");
                    let array = data.items;
                    for (let i = 0; i < array.length; i++) {
                        load_file_item(array[i], div);
                    }
                    break;
                case -1:
                    mdui.snackbar({
                        message: '未知错误' + data.message,
                    });
                    break;
                case 403:
                    nologin();
                    break;
            }
        }
    });
}

function move(uuid, name, path) {
    $.ajax({
        url: api + "/api/movefile",
        type: "POST",
        dataType: "json",
        data: {
            uuid: uuid,
            newpath: path,
            newfilename: name
        },
        success: function (data) {
            deletDom(uuid);
            switch (data.code) {
                case 0:
                    mdui.snackbar({
                        message: '已经成功移动',
                    });
                    break;
                case -1:
                    mdui.snackbar({
                        message: '移动出错' + data.message,
                    });
                    break;
                case 403:
                    nologin();
            }
        }
    });
}

function movefile(uuid, name, path) {
    mdui.prompt('你想把文件移动到哪里', '移动文件',
        function (value) {
            let strs = value.split("/");
            let new_name = strs[strs.length - 1];
            let new_path = value.substr(0, value.length - new_name.length);
            if (new_name === name && new_path === path) {
                mdui.snackbar({
                    message: '不需要移动',
                });
                return;
            }
            move(uuid, new_name, new_path);
        },
        function () {
        },
        {defaultValue: path + name}
    );
}

function deletfiles() {
    let files = $(".file-element");
    let to_delete = [];
    for (let i = 0; i < files.length; i++) {
        let checkbox = $(files[i]).find("input")[0];
        if (checkbox.checked) {
            to_delete.push(files[i].getAttribute('id'));
        }
    }
    mdui.confirm('确定要删除' + to_delete.length + "个文件？", function () {
        let success = 0;
        let real = 0;
        let failure = 0;
        let message = [];
        for (let i = 0; i < to_delete.length; i++) {
            $.ajax({
                url: api + "/api/deletefile",
                type: "POST",
                dataType: "json",
                async: false,
                data: {uuid: to_delete[i]},
                success: function (data) {
                    let item = $("#" + to_delete[i]);
                    let divider = $("#divider-" + to_delete[i]);
                    switch (data.code) {
                        case 0:
                            success++;
                            item.remove();
                            divider.remove();
                            break;
                        case 1:
                            real++;
                            item.remove();
                            divider.remove();
                            break;
                        case -1:
                            failure++;
                            message.push(data.message);
                    }
                }
            });
        }
        console.log(failure);
        console.log(real);
        console.log(success);

        if (failure === 0 && real === 0) {
            mdui.snackbar({
                message: success + '个文件已经被移动到回收站'
            });
        } else if (failure === 0 && success === 0) {
            mdui.snackbar({
                message: real + '个文件已经被删除'
            });
        } else {
            mdui.snackbar({
                message: success + '个文件被删除,' + failure + "个文件失败" + message[0]
            });
        }
    });
}

function unremove() {
    let files = $(".file-element");
    let to_unmoved = [];
    for (let i = 0; i < files.length; i++) {
        let checkbox = $(files[i]).find("input")[0];
        if (checkbox.checked) {
            let T = {};
            T.uuid = files[i].getAttribute('id');
            T.name = files[i].getAttribute('data-name');
            to_unmoved.push(T);
        }
    }
    mdui.confirm('确定要恢复' + to_unmoved.length + "个文件？", function () {
        let success = 0;
        let failure = 0;
        let message = [];
        for (let i = 0; i < to_unmoved.length; i++) {
            console.log(to_unmoved[i]);
            $.ajax({
                url: api + "/api/movefile",
                type: "POST",
                dataType: "json",
                async: false,
                data: {
                    uuid: to_unmoved[i].uuid,
                    newpath: "/",
                    newfilename: to_unmoved[i].name
                },
                success: function (data) {
                    let item = $("#" + to_unmoved[i].uuid);
                    let divider = $("#divider-" + to_unmoved[i].uuid);
                    switch (data.code) {
                        case 0:
                            success++;
                            item.remove();
                            divider.remove();
                            break;
                        case -1:
                            failure++;
                            message.push(data.message);
                    }
                }
            });
        }
        if (failure === 0) {
            mdui.snackbar({
                message: success + '个文件已经被放回根目录'
            });
        } else {
            mdui.snackbar({
                message: success + '个文件被删除,' + failure + "个文件失败" + message[0]
            });
        }
    });
}

function makepublic(uuid) {
    $.ajax({
        url: api + "/api/makepublic",
        type: "POST",
        dataType: "json",
        data: {uuid: uuid},
        success: function (data) {
            switch (data.code) {
                case 0:
                    jumpto(PATH);
                    break;
                case -1:
                    mdui.snackbar({
                        message: "操作失败" + data.message
                    });
                    break;
            }
        }
    });
}